package com.jiazhong.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiazhong.backend.service.CategoryService;
import com.jiazhong.commons.Mapper.CategoryMapper;
import com.jiazhong.commons.Util.JsonResult;
import com.jiazhong.commons.Util.ResultTool;
import com.jiazhong.commons.bean.Book;
import com.jiazhong.commons.bean.Category;
import com.jiazhong.commons.exception.*;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Override
    public JsonResult findPage(int page, int size) {
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.select("id","name","sort","status");
        Page<Category> of = Page.of(page,size);
        List<Category> list = list(of,wrapper);
        of.setRecords(list);
        if (list==null||list.size()==0){
            throw new CategoryNotFoundException("没有找到该类书籍");
        }
        return ResultTool.success(of);
    }

    @Override
    public JsonResult findSearch(String name, int page, int size) {
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.select("id","name","sort","status");
        wrapper.like("name",name);
        Page<Category> of = Page.of(page,size);
        List<Category> list = list(of,wrapper);
        of.setRecords(list);
        if (list==null||list.size()==0){
            throw new CategoryNotFoundException("没有找到该类书籍");
        }
        return ResultTool.success(of);
    }

    @Override
    public JsonResult saveCategory(Category category) {
        boolean save = save(category);
        if (!save){
            throw new CategorySaveException("添加类别失败");
        }
        return ResultTool.success("success");
    }

    @Override
    public JsonResult removeCategory(String id) {
        boolean b = removeById(id);
        if (!b){
            throw new CategorySaveException("添加类别失败");
        }
        return ResultTool.success("success");
    }

    @Override
    public JsonResult findExists(String colum, String value) {
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.eq(colum,value);
        wrapper.select("count(0)");
        Map<String,Object> map = getMap(wrapper);
        int row = Integer.parseInt(map.get("count(0)").toString());
        if (row==1){
            throw new CategoryExistsException(colum+"已经存在");
        }
        return ResultTool.success("success");
    }
}
